<template>
  <div class="app-page">
    <div style="padding: 10px 0;">
      <el-button style=" display: inline-block; width: 150px;" :type="type === 'three' ? 'primary' : 'default'" @click="queryTime('three')">近三天</el-button>
      <el-button style="display: inline-block; width: 150px;" :type="type === 'week' ? 'primary' : 'default'" @click="queryTime('week')">近七天</el-button>
      <el-button style="display: inline-block; width: 150px;" :type="type === 'month' ? 'primary' : 'default'" @click="queryTime('month')">近一个月</el-button>
    </div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="" prop="" :table-form-merge="2">
        <el-select v-model="choose" placeholder="" style="width: 30%;">
          <el-option
            v-for="item in chooseMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="inpuntText"
          style="width: 68%;"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="申诉来源" prop="appealFrom">
        <el-select
          v-model="query.appealFrom"
          filterable
          placeholder="请选择"
          style="width: 100%;"
          clearable
        >
          <el-option
            v-for="item in appealFromMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申诉原因" prop="appealReason">
        <el-select
          v-model="query.appealReason"
          filterable
          placeholder="请选择"
          style="width: 100%;"
          clearable
        >
          <el-option
            v-for="item in appealReasonMap"
            :key="item.keyId"
            :label="item.keyName"
            :value="item.keyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申诉时间" prop="" :table-form-merge="2">
        <!-- <el-select v-model="query.statusType" placeholder="请选择" @change="chooseType">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-date-picker
          v-model="query.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :editable="false"
          :clearable="false"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>

      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </template>
    </el-table-form>
    <!-- <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="6" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div> -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
    />
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="search"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <!-- <oneHouseOneCodeDetail ref="oneHouseOneCodeDetail" /> -->
    <appealDetail ref="appealDetail" />
    <!-- <chooseAddress ref="chooseAddress" @refresh="search" /> -->
  </div>
</template>

<script>
  import { queryMap,
           queryDictionaries,
           queryAppealList,
           unBindOneHouseOneCode,
           allowSignOneHouseOneCode,
           avoidOneHouseOneCode,
           exportOneHouseOneCode,
           selectAreaCode,
           queryTransactorList,
           appealQueryNew,
           queryExportDomain } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import OrderDetail from '@/views/orderCenter/orderManage/components/OrderDetails'
  //   import oneHouseOneCodeDetail from './components/oneHouseOneCodeDetail'
  import appealDetail from '@/views/customerCenter/oneHouseOneCodeAppeal/components/appealDetail'
  //   import chooseAddress from './components/chooseAddress'

  export default {
    name: 'oneHouseOneCodeAppeal',
    components: {
      CsmDetail,
      OrderDetail,
      //   oneHouseOneCodeDetail,
      appealDetail
    // chooseAddress
    },
    filters: {},
    data() {
      return {
        treeData: [],
        choose: 'csmPhone',
        type: 'three',
        inpuntText: '',
        chooseMap: [
          { desc: '订单号', value: 'billCode' },
          { desc: '客户电话', value: 'csmPhone' },
          { desc: '客户编号', value: 'csmCode' },
          { desc: '客户名称', value: 'csmName' },
          { desc: '申诉号', value: 'appealCode' }
        ],
        opStatusSourceMap: [], // 状态枚举
        appealFromMap: [], // 来源枚举
        appealReasonMap: [], // 原因枚举
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        transactorList: [], // 处理人列表
        orderStatusMap: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        query: {
          appealFrom: null,
          appealReason: null,
          opStatusSource: [1],
          orgSNNo: '',
          timeRange: []
        },
        tableData: {
          data: [],
          column: [
            {
              type: 'index',
              align: 'center',
              fixed: 'left'
            },
            {
              prop: 'appealCode',
              label: '申诉号',
              fixed: 'left',
              width: 100,
              showOverflowTooltip: true,
              render: (h, { row }) => (
                row.appealCode ? <el-link underline={false} onClick={() => this.openAppeal(row)}>
              {row.appealCode}
                </el-link> : <span>{row.appealCode}</span>
              )
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 110,
              render: (h, { row }) => (
                row.csmCode ? <el-link underline={false} onClick={() => this.openCsm(row)}>
                  {row.csmCode}
                </el-link> : <span>{row.csmCode}</span>
              )
            },
            {
              prop: 'billCode',
              label: '关联订单',
              width: 110,
              render: (h, { row }) => (
                row.billCode ? <el-link underline={false} onClick={() => this.openBill(row)}>
                  {row.billCode}
                </el-link> : <span>{row.billCode}</span>
              )
            },
            {
              prop: 'bindStatus',
              label: '是否绑定',
              render: (h, { row }) => <span>{ row.bindStatus === 1 ? '未绑定' : '已绑定'}</span>
            },
            {
              prop: 'csmName',
              label: '客户名称',
              showOverflowTooltip: true
            },
            {
              prop: 'orgName',
              label: '所属机构',
              showOverflowTooltip: true
            },
            {
              prop: 'appealFrom',
              label: '申诉来源',
              render: (h, { row }) => <span>{row.appealFrom ? formatColumnMap(this.appealFromMap, 'value', row.appealFrom, 'desc') : '' }</span>
            },
            {
              prop: 'appealName',
              label: '申诉人',
              showOverflowTooltip: true
            },
            {
              prop: 'appealReason',
              label: '申诉原因',
              render: (h, { row }) => <span>{row.appealReason ? formatColumnMap(this.appealReasonMap, 'keyId', row.appealReason, 'keyName') : '' }</span>
            },
            {
              prop: 'remark',
              label: '备注',
              showOverflowTooltip: true
            },
            {
              prop: 'csmPhone',
              label: '客户电话',
              showOverflowTooltip: true
            },
            {
              prop: 'oldAddress',
              label: '变更前地址',
              showOverflowTooltip: true
            },
            {
              prop: 'newAddress',
              label: '变更后地址',
              showOverflowTooltip: true
            },
            {
              prop: 'appealDt',
              label: '申诉时间',
              width: 160,
              render: (h, { row }) => <span>{ row.appealDt && parseTime(row.appealDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            }
            // {
            //   prop: 'opertorName',
            //   label: '处理人',
            //   showOverflowTooltip: true
            // },
            // {
            //   prop: 'opertorDt',
            //   label: '处理时间',
            //   width: 160,
            //   render: (h, { row }) => <span>{ row.opertorDt && parseTime(row.opertorDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            // },
            // {
            //   prop: 'opStatus',
            //   label: '状态',
            //   render: (h, { row }) => <span>{row.opStatus ? formatColumnMap(this.opStatusSourceMap, 'value', row.opStatus, 'desc') : '' }</span>
            // }
          ]
        },
        addressProps: {
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then(res => {
                const nodes = res.data.map(item => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ])
    },
    activated() {
      this.queryNew()
      this.interval = setInterval(() => {
        this.queryNew()
      }, 60000)
    },
    deactivated() {
      clearInterval(this.interval)
    },
    async created() {
      await this.getTimeFn()
      await Promise.all([this.queryOptionsMap()])
      await this.getTreeData()
      this.query.orgSNNo = this.userInfo.orgSNNo
      this.getExportDomain()
      this.queryTime(this.type)
    },
    methods: {
      queryTime(type) {
        this.type = type
        if (type === 'three') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
          this.query.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
        if (type === 'week') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          this.query.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
        if (type === 'month') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          this.query.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8, res9] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CsmQRAppealFrom' }),
          mergeAsyncFunc(queryMap, { enumName: 'CsmQROpStatus' }),
          mergeAsyncFunc(queryDictionaries, { commonKeys: 6 }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.appealFromMap = res1.data // 申诉来源枚举
        this.opStatusSourceMap = res2.data // 状态枚举
        this.appealReasonMap = res3.data // 原因枚举
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.orderStatusMap = res6.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res7.data // 订单类型
        this.payStatusMap = res8.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res9.data // 订单来源
        this.getTransactorList()
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.query.timeRange[0] = parseTime(start, '{y}-{m}-{d}') + ' 00:00:00'
        this.query.timeRange[1] = parseTime(end, '{y}-{m}-{d}') + ' 23:59:59'
      },
      _getQuery(obj) {
        const query = {}
        if (this.choose === 'billCode') {
          query.billCode = this.inpuntText
        }
        if (this.choose === 'csmPhone') {
          query.csmPhone = this.inpuntText
        }
        if (this.choose === 'csmCode') {
          query.csmCode = this.inpuntText
        }
        if (this.choose === 'csmName') {
          query.csmName = this.inpuntText
        }
        if (this.choose === 'appealCode') {
          query.appealCode = this.inpuntText
        }
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'timeRange') {
                if (obj['timeRange']) {
                  if (obj['timeRange'].length > 0) {
                    query['appealDt'] = new Date(obj[key][0])
                    query['appealDtEnd'] = new Date(obj[key][1])
                  }
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          paramJson: {
            ...this._getQuery(this.query)
          },
          pageIndex: currentPage,
          pageSize
        }
        if (!query.paramJson.appealDt || !query.paramJson.appealDtEnd) {
          this.$message.error('请选择查询时间')
          return
        }
        const res = await queryAppealList(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      // 搜索
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.opStatus === 1) {
          // 待处理
          return 'red-row'
        }
        return ''
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm('确定导出数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.tableData.column))
          list.pop()
          list.shift()
          const value = {}
          await list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const query = {
            paramInfo: {
              ...this._getQuery(this.query)
            },
            kv: value
          }
          await exportOneHouseOneCode(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 打开关联订单
      async openBill(row) {
        row.orderCode = row.billCode
        await this.$refs.orderDetail.open(row, true)
      },
      // 打开申诉
      async openAppeal(row) {
        await this.$refs.appealDetail.open(row, true)
        this.search()
      },
      // 流转信息
      async openDetail(row) {
        row.orderCode = row.billCode
        await this.$refs.oneHouseOneCodeDetail.open(row)
      },
      reset() {
        this.$refs.form.resetFields()
        this.choose = 'csmPhone'
        this.inpuntText = ''
        this.query.appealFrom = null
        this.query.appealReason = null
        this.query.opStatusSource = [1]
        this.query.orgSNNo = null
        this.query.timeRange = []
        this.getTimeFn()
      },
      // 解绑
      unBind(row) {
        this.$confirm(`您确认解绑吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          unBindOneHouseOneCode({ appealCode: row.appealCode }).then(res => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            console.log(err)
          })
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      // 允许签收
      allowSign(row) {
        this.$confirm(`您确认允许签收吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          allowSignOneHouseOneCode({ appealCode: row.appealCode }).then(res => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
          }).catch(err => { console.log(err) })
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      // 作废
      avoidOne(row) {
        this.$confirm(`您确认作废吗?`, '提示', {
          type: 'warning'
        }).then(() => {
          avoidOneHouseOneCode({ appealCode: row.appealCode }).then(res => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: `操作成功`,
              type: 'success',
              duration: 2000
            })
          }).catch(err => { console.log(err) })
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      chooseAddress(row) {
        this.$refs.chooseAddress.open(row)
      },
      // 查询是否有未处理的单子
      async queryNew() {
        const res = await appealQueryNew()
        console.log(res)
        if (res.data && JSON.stringify(res.data) !== '{}') {
          const dom = document.getElementById('newAppeal')
          dom.play()
        }
      }
    }
  }
</script>

<style scoped lang="scss">
.app-page {
  padding: 0 10px;
}
/deep/ .el-table tr.red-row {
  background: #ffeced;
}
</style>
